package com.minivision.migrate.config;

import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;

@Order(1)
@Data
@Slf4j
@Configuration
@ConfigurationProperties(prefix = "ssh.forward")
public class SshConfiguration {

    private String username;

    private String password;

    private String host;

    private Integer port;

    private boolean enabled;

    private String privateKeyFileName = "privateKey";

    private String privateKeyPassphrase = "D7JqJzHQmdmNe4ru";

    private String fromHost;
    private Integer fromPort;

    private String toHost;
    private Integer toPort;

    @Bean
    public Session sessionInit() {
        try {
            //如果配置文件包含ssh.forward.enabled属性，则使用ssh转发
            if (enabled) {
                log.info("ssh forward is opend.");
                log.info("ssh init ……");
                JSch jSch = new JSch();
                String path = this.getClass().getClassLoader().getResource(privateKeyFileName).getPath();
                jSch.addIdentity(path, privateKeyPassphrase);
                Session session = jSch.getSession(username, host, port);
                session.setConfig("StrictHostKeyChecking", "no");
                session.setPassword(password);
                session.connect();
                session.setPortForwardingL(fromHost, fromPort, toHost, toPort);
                return session;
            } else {
                log.info("ssh forward is closed.");
            }
        } catch (JSchException e) {
            log.error("ssh JSchException failed.", e);
        } catch (Exception e) {
            log.error("ssh settings is failed. skip!", e);
        }
        return null;
    }
}